using System.IdentityModel.Tokens.Jwt;
using System.Text;
using LocalTest.Domain.Interfaces;
using LocalTest.Infrastructure.Context;
using LocalTest.Web.Extensions;
using LocalTest.Web.Middleware;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace LocalTest.Web;

public class Program
{
    public static void Main(string[] args)
    {
        // todo:
        // jwt 鉴权完成后获取用户信息 从redis中
        // jwt 完成后，如果redis为空，失败

        JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
        {
            ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() },
            DateFormatString = "yyyy-MM-dd HH:mm:ss"
        };

        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddAuthentication().AddJwtBearer(option =>
        {
            option.TokenHandlers.Clear();
            option.TokenHandlers.Add(new RedisTokenHandler());
            option.TokenValidationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
                ValidateIssuer = true,
                ValidateActor = true,
                ValidIssuer = builder.Configuration["Jwt:Issuer"],
                ValidAudience = builder.Configuration["Jwt:Audience"],
            };
        });

        // Add services to the container.
        builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        }).AddNewtonsoftJson((option) =>
        {
            option.SerializerSettings.ContractResolver = new DefaultContractResolver
                { NamingStrategy = new SnakeCaseNamingStrategy() };
            option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
        });
        // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
        builder.Services.AddOpenApi();
        builder.Services.AddDbContext<AppDbContext>(ServiceLifetime.Scoped);
        builder.UseAuthUserMiddlewareService();


        var app = builder.Build();
        app.UseRouting();

        app.UseUrlEncodeDataKey();
        app.UseAuthUserMiddleware();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.MapOpenApi();
        }

        // app.UseHttpsRedirection();

        app.UseAuthentication();

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}